<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="130px">
      <el-form-item label="模板名称" prop="template_name">
        <el-input v-model="form.template_name" style="width: 350px;" />
        <el-row style="font-size:13px;color:#909399">除指定地区外，其余地区的运费采用“默认运费”</el-row>
      </el-form-item>
      <el-form-item label="默认运费" prop="default_freight">
        <el-input v-model="form.default_freight" style="width: 350px"/>
        <span style="font-size:13px;color:#909399">元</span>
      </el-form-item>
      <el-form-item label="配送区域">
        <el-table :data="areaList" size="mini" style="width:960px">
          <el-table-column prop="area" label="配送区域" width="660"/>
          <el-table-column width="120">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="doEditArea(scope.row, scope.$index)">编辑</el-button>
              <el-button type="text" size="small" @click="doDeleteArea(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="运费" fixed="right" width="180">
            <template slot-scope="scope">
              <input v-model="scope.row.freight" type="text" size="small" @change="changeFreight(scope.row.freight, scope.$index)">
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="doOpenArea">指定可配送区域和运费</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doSubmit">保存</el-button>
        <el-button @click="doBack">返回</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      title="选择配送区域"
      width="60%"
      height="500">
      <el-cascader-panel
        ref="areaLabel"
        :options="area"
        :props="props"
        v-model="selectedOptions"
        collapse-tags
        style="width: 100%;"
        clearable
        @change="handleChange"/>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="doCancelArea">取 消</el-button>
        <el-button size="small" type="primary" @click="doSubmitArea">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import area from '@/api/mall/area.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { updateFreight } from '@/api/mall/shopconfigRequest'
export default {
  components: { Treeselect },
  props: {
  },
  data() {
    return {
      props: { multiple: true },
      area: [], // 区域选择数据
      selectedOptions: [], // 选中的区域
      areaList: [], // 配送区域列表
      dialogVisible: false,
      areaListItem: {}, // 数组单挑数据
      index: null, // 配送区域列表index
      form: {
        template_name: '',
        default_freight: ''
      },
      rules: {
        template_name: [
          { required: true, message: '请输入模版名称', trigger: 'change' }
        ],
        default_freight: [
          { required: true, message: '请输入运费', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.formatArea()
  },
  methods: {
    formatArea() {
      const data = area.area
      this.area = data.map(item => {
        return {
          value: item.index + '/' + item.provinces.length + '/' + item.part,
          label: item.part,
          children: item.provinces.map(item => {
            return {
              value: item.regionId + '/' + item.cities.length + '/' + item.name,
              label: item.name,
              children: item.cities.map(item => {
                return {
                  value: item.regionId + '/' + item.counties.length + '/' + item.name,
                  label: item.name,
                  children: item.counties.map(item => {
                    return {
                      value: item.regionId + '/0/' + item.name,
                      label: item.name
                    }
                  })
                }
              })
            }
          })
        }
      })
    },
    // 选择地区change事件改变
    handleChange(value) {
      this.areaValue = value
      // console.log('areaValue', this.areaValue)
      // 组装后的树
      const result = []
      // 遍历数据源，每一条数据从根节点id到当前节点id，形如：[[0, 21, 2101, 210102],[0, 21, 2101, 210103]]
      value.map(function(d) {
        // 结果集往下传递-
        let temp = result
        // console.log(JSON.stringify(temp))
        // 遍历每一条数据的每个节点id,形如：[0, 21, 2101, 210102]
        d.map(function(d2) {
          // 获取
          let _pos = -1
          // 遍历已经拼装好的数据，id为map的key,判断key是否存在，存在返回key的游标
          temp.map(function(d, i) {
            if (d.id === d2) {
              _pos = i
            }
          })
          // console.log(d2 + '        ' + _pos)
          // 向原节点写值
          if (_pos !== -1) {
            // 当当前节点已经存在该值时，不做储存，把当前节点的下一个节点children数组向下传递
            // console.log(JSON.stringify(temp[_pos]['children']))
            temp = temp[_pos]['children']
          } else {
            // 对当前节点不存该值时，为当前节点存入该值，并把父节点向下传递
            temp.push({
              'id': d2,
              'children': []
            })
            // console.log(JSON.stringify(temp))
            temp = temp[temp.length - 1]['children']
          }
        })
      })
      const list = []
      // console.log(result)
      // 思维：树形数据结构，那么要想满足下级全部勾选，只显示上级的结构，那么就的
      // 1：逐层紧挨着遍历
      // 2.从最下级做判断，
      //  2-1.下级勾选的个数是否与原数据应有的个数相等，不相等返回false
      //  2-2.遍历上一层时判断他的下一层是否有不没有全选，若有，则也返回false，此时依次往上层递归，逐层都要保留
      // 以下遍历区域
      result.map(function(d) {
        // 如果 1.市不是全选，则区域要保留所选中的省 2.省虽然全选但是下级有处于未全选的，则需要保留省
        let province = true
        // 以下遍历省
        d['children'].map(function(d1) {
          // 以下遍历市
          // 如果 1.县不是全选，则区域要保留所选中的市 2.市虽然全选但是下级有处于未全选的，则需要保留市
          let city = true
          d1['children'].map(function(d2) {
            // 市中县的个数
            const num = Number(d2['id'].split('/')[1])
            // 判断区是否全选
            if (num === d2['children'].length) {
              d2['children'] = []
            } else {
              // 如果县有数据，则全路都存
              d2['children'].map(function(d3) {
                list.push(d.id + '-' + d1.id + '-' + d2.id + '-' + d3.id)
              })
              city = false
            }
          })
          // 省中市的个数
          const num = Number(d1['id'].split('/')[1])
          // 判断市是否全部选中状态，且市里的县也是全勾选状态
          if (num === d1['children'].length && city) {
            d1['children'] = []
          } else {
            // 如果市下面没有数据，则代表，市全选了，存市
            d1['children'].map(function(d2) {
              if (d2['children'].length === 0) {
                list.push(d.id + '-' + d1.id + '-' + d2.id)
              }
            })
            province = false
          }
        })
        // 区域中省的个数
        const num = Number(d['id'].split('/')[1])
        // 判断省是否全部选中状态，且省里的市也是全勾选状态
        if (num === d['children'].length && province) {
          d['children'] = []
        } else {
          // 省下面没有了市的数据，代表市全选了，存省
          d['children'].map(function(d1) {
            if (d1['children'].length === 0) {
              list.push(d.id + '-' + d1.id)
            }
          })
          province = false
        }
        // 区域下面没有了省的数据，代表市全选了，存区域
        if (d['children'].length === 0) {
          list.push(d.id)
        }
      })
      // 树结构
      // 扁平化数据
      this.areaListItem = {
        area: this.getData(list),
        default_freight: '',
        selectedOptions: this.areaValue
      }
    },
    // 将数组字符串转成以逗号分割的字符串  ['我们的/故事', ‘从什么时候/开始’] ==> '故事，开始'
    getData(arr) {
      let data = ''
      arr.map((item) => {
        data += item.split('/')[item.split('/').length - 1] + '，'
      })
      return data
    },
    // 配送区域弹框确定
    doSubmitArea() {
      console.log()
      if (this.index != null) {
        if (this.selectedOptions.length === 0) {
          this.$message({
            message: '请选择城市',
            type: 'warning'
          })
          return
        } else {
          this.areaList[this.index].area = this.areaListItem.area
          this.areaList[this.index].selectedOptions = this.areaListItem.selectedOptions
          this.index = null
        }
      } else {
        if (this.selectedOptions.length === 0) {
          this.$message({
            message: '请选择城市',
            type: 'warning'
          })
          return
        } else {
          this.areaList.push(this.areaListItem)
        }
      }
      this.dialogVisible = false
    },
    // 配送区域弹框取消
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
          this.selectedOptions = []
          this.areaListItem = {}
        })
        .catch(_ => {})
    },
    // 删除配送区域
    doDeleteArea(index) {
      this.areaList.map((item, i) => {
        if (i === index) {
          this.areaList.splice(item, 1)
        }
      })
    },
    // 编辑配送区域
    doEditArea(row, index) {
      this.dialogVisible = true
      this.index = index
      this.selectedOptions = row.selectedOptions
    },
    changeFreight(value, index) {
      this.areaList[index].freight = value
    },
    // 打开选择配送区域弹框
    doCancelArea() {
      this.dialogVisible = false
      this.selectedOptions = []
      this.areaListItem = {}
    },
    // 关闭选择配送区域弹框
    doOpenArea() {
      this.dialogVisible = true
      this.selectedOptions = []
      this.areaListItem = {}
    },
    // 新增模版保存
    doSubmit() {
      if (this.form.default_freight === '' || this.form.template_name === '') {
        this.$notify({
          title: '模板名称或默认运费不能为空',
          type: 'success',
          duration: 2500
        })
        return
      }
      this.$refs['form'].validate((valid) => {
        this.form.area = this.areaList
        this.form.default_freight = this.form.default_freight
        this.form.template_name = this.form.template_name
        this.doAdd()
      })
    },
    // 新增模版返回
    doBack() {
      this.$parent.isAddFreightShow = false
    },
    doAdd() {
      updateFreight(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.$parent.isAddFreightShow = false
        this.$parent.getFreightList()
      })
    },
    resetForm() {
      this.dialog = false
      this.form = {
        number: '',
        contacts: '',
        landline_telephone: '',
        province: '',
        city: '',
        street: '',
        type: '',
        tel: ''
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
/deep/ .el-input-number .el-input__inner {
  text-align: left;
}
</style>
